var PORT = 3000;
//请访问 localhost:3000
//https://blog.csdn.net/gfei1234/article/details/100105708
var http = require("http");
var url = require("url");
var fs = require("fs");
var mine = require("./mine").types;
var path = require("path");
var querystring = require("querystring");
const { log } = require("console");

var server = http.createServer(function (request, response) {
  var pathname = url.parse(request.url).pathname;
  var realPath = path.join("view", pathname);
  var ext = path.extname(realPath);
  ext = ext ? ext.slice(1) : "unknown";
  // fs.exists(realPath, function (exists) {
  //   if (!exists) {
  //     response.writeHead(404, {
  //       "Content-Type": "text/plain",
  //     });

  //     response.write(
  //       "This request URL " + pathname + " was not found on this server."
  //     );
  //     response.end();
  //   } else {
  //     fs.readFile(realPath, "binary", function (err, file) {
  //       if (err) {
  //         response.writeHead(500, {
  //           "Content-Type": "text/plain",
  //         });
  //         response.end(err);
  //       } else {
  //         var contentType = mine[ext] || "text/plain";
  //         console.log(contentType);
  //         response.writeHead(200, {
  //           "Content-Type": contentType,
  //         });
  //         response.write(file, "binary");
  //         response.end();
  //       }
  //     });
  //   }
  // });
  if (request.method == "GET") {
    var rs = fs.readFileSync("./view/index.html", "utf-8");
    var params = url.parse(request.url).query;
    var paramObj = querystring.parse(params);
    console.log(params);
    console.log(paramObj);
    var rs = rs.replace("<%=query%>", paramObj.id);
    response.write(rs);
    response.end();
  } else if (request.method == "POST") {
    // var rs = fs.readFileSync("./view/index.html", "utf-8");
    // var params = url.parse(request.url).query;
    // var paramObj = querystring.parse(params);
    // console.log(params);
    // console.log(paramObj);
    // var rs = rs.replace("<%=query%>", paramObj.id);
    // response.write(rs);
    response.end();
  }
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");
